package com.homestead.utils;

import java.security.MessageDigest;
import java.util.*;

/**
 * @author yhb
 * @date 2021-05-28 12:23
 */
public class SecurityVerifyUtil {
    public static String geAuthCode(final String securityClientCode, final String securityClientSecret,
                                    final long reqTime, final Map<String, Object> reqDataMap) {
        final Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("client_code", securityClientCode);
        dataMap.put("client_secret", securityClientSecret);
        dataMap.put("req_time", reqTime + "");
        if(null != reqDataMap) {
            for (Map.Entry<String, Object> entry : reqDataMap.entrySet()) {
                final String key = entry.getKey();
                if (!key.equals("authcode") && !key.equals("client_code") && !key.equals("client_secret") && !key.equals("req_time")) {
                    dataMap.put(key.toLowerCase(), String.valueOf(entry.getValue()));
                }
            }
        }

        final SortedMap<String, Object> sortedMap = new TreeMap<>(dataMap);

        List<String> keys = new ArrayList<>(sortedMap.keySet());
        Collections.sort(keys);

        StringBuilder bMd5Str = new StringBuilder();
        for (String key : keys) {
            String value = dataMap.get(key).toString();
            if (null != value && !"".equals(value)) {
                bMd5Str.append(value);
            }
        }

        return Objects.requireNonNull(MD5(bMd5Str.toString())).toLowerCase();
    }

    public static String MD5(final String s) {
        final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            final byte[] btInput = s.getBytes("UTF-8");
            final MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            final byte[] md = mdInst.digest();
            final int j = md.length;
            final char[] str = new char[j * 2];
            int k = 0;
            for (final byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xF];
                str[k++] = hexDigits[byte0 & 0xF];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

